package com.starlink.service;

import com.starlink.common.annotation.client.WeixinJsClient;
import com.starlink.common.annotation.client.weixin.WeixinPayNotifyReq;
import com.starlink.common.annotation.client.weixin.WeixinPayNotifyRes;
import com.starlink.common.annotation.client.weixin.WeixinRefundNotifyReq;
import com.starlink.common.annotation.client.weixin.WeixinRefundNotifyRes;
import com.starlink.common.config.WechatConfigurationConfig;
import com.starlink.utils.AesUtil;
import com.starlink.utils.FastJsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.Charset;

/**
 * 用户支付服务
 *
 * @author zhanghong
 * @version XcxUserPayService.java, v 0.1 2022/4/6 14:39 下午 XcxUserPayService Exp $$
 */
@Slf4j
@Service
public class XcxUserPayService {
    @Autowired
    private WeixinJsClient weixinJsClient;

    /**
     * 微信支付通知
     *
     * @param req
     * @return
     */
    @Transactional
    public WeixinPayNotifyRes weixinPayNotify(WeixinPayNotifyReq req) {
        try {
            //1.解析支付通知数据：得到业务侧商户订单号
            WeixinPayNotifyReq.Resource resource = req.getResource();
            if (resource == null) {
                return WeixinPayNotifyRes.ERR_RES;
            }
            String decryptStr = AesUtil.decryptToString(resource.getAssociated_data().getBytes(Charset.forName("UTF-8")),
                    resource.getNonce().getBytes(Charset.forName("UTF-8")),
                    resource.getCiphertext(),
                    WechatConfigurationConfig.wxUserWechatApiV3Key);
            log.info("weixinPayNotify decryptStr: {}", decryptStr);
            WeixinPayNotifyReq.DecryptResource decryptResource = FastJsonUtils.fromJSONString(decryptStr, WeixinPayNotifyReq.DecryptResource.class);
            if (!"SUCCESS".equalsIgnoreCase(decryptResource.getTrade_state())) {
                log.info("weixinPayNotify 支付订单状态不成功");
                return WeixinPayNotifyRes.ERR_RES;
            }

            //2.查询订单数据
            String payOrderType = decryptResource.getAttach();
            String payOrderNum = decryptResource.getOut_trade_no();
            if (StringUtils.isAnyBlank(payOrderType, payOrderNum)) {
                log.error("weixinPayNotify 商户系统订单号编号or订单类型为空 mainOrderNum={} payOrderType={}", payOrderNum, payOrderType);
                return WeixinPayNotifyRes.ERR_RES;
            }

            // TODO 订单后续处理
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return WeixinPayNotifyRes.SUC_RES;
    }

//    public void findTemplate1(XcxGoodsOrder order){
//        try { //模板消息 sendTemplate1 新订单通知
//            String firstElement = redisService.listGetHeadElement(order.getOrderNum());
//            if (firstElement == null || StringUtils.isEmpty(firstElement)) {
//
//            }else{
//                XcxEngineer engineer = xcxEngineerMapper.selectXcxEngineerById(Long.parseLong(firstElement));
//                String mobile="";
//                String name="";
//                if(order.getAddressId()!=null){
//                    XcxAddress address = xcxAddressMapper.selectXcxAddressById(order.getAddressId());
//                    if(address!=null){
//                        mobile=address.getMobile();
//                        name=address.getLinkMan();
//                    }
//                }
//
//                wxTemplateService.sendTemplate1(engineer.getUnionId(),
//                        name,
//                        mobile,
//                        "",
//                        "",
//                        "pages/index/index",
//                        "您有一个新订单，请接单！"
//                );
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 微信退款通知
     *
     * @param req
     * @return
     */
    @Transactional
    public WeixinRefundNotifyRes weixinRefundNotify(WeixinRefundNotifyReq req) {
        try {
            //1.解析退款通知数据：得到业务侧商户退款单号
            WeixinRefundNotifyReq.Resource resource = req.getResource();
            if (resource == null) {
                return WeixinRefundNotifyRes.ERR_RES;
            }
            String decryptStr = AesUtil.decryptToString(resource.getAssociated_data().getBytes(Charset.forName("UTF-8")),
                    resource.getNonce().getBytes(Charset.forName("UTF-8")),
                    resource.getCiphertext(),
                    WechatConfigurationConfig.wxUserWechatApiV3Key);
            log.info("weixinRefundNotify decryptStr: {}", decryptStr);
            WeixinRefundNotifyReq.DecryptResource decryptResource = FastJsonUtils.fromJSONString(decryptStr, WeixinRefundNotifyReq.DecryptResource.class);
            if (!"SUCCESS".equalsIgnoreCase(decryptResource.getRefund_status())) {
                log.info("weixinRefundNotify 退款订单状态不成功");
                return WeixinRefundNotifyRes.ERR_RES;
            }

            //2.查询退款订单数据
            String refundOrderNum = decryptResource.getOut_refund_no();
            if (StringUtils.isBlank(refundOrderNum)) {
                log.error("weixinRefundNotify 微信返回的商户系统out_refund_no订单号为空");
                return WeixinRefundNotifyRes.ERR_RES;
            }

           // TODO 退款后续处理
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return WeixinRefundNotifyRes.SUC_RES;
    }


    /**
     * 退款
     * @param refundMoney
     * @param totalPayMoney
     * @param order
     * @return
     */
//    public boolean refundOrderMoney(Double refundMoney, Double totalPayMoney, XcxGoodsOrder order) {
//        log.info("refundOrderMoney 微信退款 refundMoney={}  totalPayMoney={}", refundMoney, totalPayMoney);
//        log.info("refundOrderMoney 微信退款 order_num={}, cancel_reason={}", order.getOrderNum(), order.getCancelReason());
//
//        if (refundMoney <= Constants.ZERO) {
//            log.info("refundOrderMoney 退款金额<=0 --> 无需退款");
//            return true;
//        }
//
//        //解析orderDetail
//        AssertUtil.assertTrue(JSONUtil.isJson(order.getOrderDetailInfo()), ErrorCode.PARAM_ERROR, "下单数据有误, 退款失败");
//        OrderDetailInfo orderDetailInfo = JSON.parseObject(order.getOrderDetailInfo(), OrderDetailInfo.class);
//
//        //退款金额
//        RefundAmount refundAmount = new RefundAmount();
//        refundAmount.setRefund(MoneyUtil.yuan2fen(refundMoney));
//        refundAmount.setTotal(MoneyUtil.yuan2fen(totalPayMoney));
//
//        //退款商品
//        RefundAmountGoodsDetail detail = new RefundAmountGoodsDetail();
//        detail.setMerchant_goods_id(String.valueOf(orderDetailInfo.getGoodsId()));
//        detail.setGoods_name(orderDetailInfo.getGoodsName());
//        if (orderDetailInfo.getGoodsPrice().equals(0d)) {
//            orderDetailInfo.setGoodsPrice(refundMoney);
//        }
//        detail.setUnit_price(MoneyUtil.yuan2fen(orderDetailInfo.getGoodsPrice()));
//        //detail.setRefund_amount(MoneyUtil.yuan2fen(orderDetailInfo.getGoodsItemPayMoney()));
//        detail.setRefund_amount(MoneyUtil.yuan2fen(refundMoney));
//        detail.setRefund_quantity(orderDetailInfo.getGoodsNum());
//        detail.setWechatpay_goods_id(StrUtil.toString(orderDetailInfo.getGoodsId()));
//
//        log.info("refundOrderMoney 微信退款 RefundAmountGoodsDetail={}", JSON.toJSONString(detail));
//        log.info("refundOrderMoney 微信退款 RefundAmount={}", JSON.toJSONString(refundAmount));
//        try {
//            WeixinJsRefundOrderReq req = WeixinJsRefundOrderReq.weixinJsRefundOrderReq(order, refundAmount, Lists.newArrayList(detail));
//            WeixinJsRefundOrderRes res = weixinJsClient.createRefundOrder(req);
//            log.info("申请退款res {}", res);
//            //退款信息更新到订单
//            String wxRefundId = res.getRefund_id();
//            String wxRefundStatus = res.getStatus();
//            Double wxRefundMoney = refundMoney;
//            String refundNum = order.getRefundNum();
//            xcxGoodsOrderMapper.updateApplyRefundInfoByOrderNum(order.getOrderNum(), wxRefundId, wxRefundStatus, wxRefundMoney, refundNum);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERR_REFUND, "退款失败");
//        }
//        return true;
//    }
}
